//
//  ProductInfoViewController.m
//  PagingDemo
//
//  Created by Liu jinyong on 15/8/6.
//  Copyright (c) 2015年 Baidu 91. All rights reserved.
//

#import "ProductInfoViewController.h"
#import "UIScrollView+JYPaging.h"
#import "ProductDetailViewController.h"
#import "DCPicScrollView.h"
#import "CustomCommentTableViewCell.h"
#import "MyCommentViewController.h"
#import "ProductRightNaviView.h"
#import "MBProgressHUD.h"
#import "ProdcutDetaiModel.h"
#import "CommentModel.h"
#import "ShopBagViewController.h"
#import "PurchaseNowViewController.h"
#import "ShareView.h"
#import "AppContext.h"
#import "CartCountModel.h"
#import "LoginViewController.h"
#import "SDCycleScrollView.h"
#import "CLZRefreshHeader.h"
@interface ProductInfoViewController ()<UIScrollViewDelegate,PurchaseCommodityDelegate>
@property (nonatomic, copy) NSString *productId;
@property (nonatomic, strong) ProdcutDetaiModel *productModel;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *picViewContainer;
@property (nonatomic, strong) SDCycleScrollView *picView;
@property (weak, nonatomic) IBOutlet UIView *commentViewContainer;
@property (weak, nonatomic) IBOutlet UIView *purchaseView;
@property (nonatomic, assign) int lastPosition;

@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *standardPriceTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *standardPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *chunlaiTextLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *commenterAvatarIV;
@property (weak, nonatomic) IBOutlet UILabel *commenterNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *commentContentLabel;

@property (weak, nonatomic) IBOutlet UIButton *bottomBtn;
@property (nonatomic, strong) ProductRightNaviView *rightNaviView;
@property (nonatomic, strong) ShareView *shareView;
@property (nonatomic, strong) PurchaseNowViewController *purchaseVC;
@property (nonatomic, assign) NSInteger productNumberInCart;
@end

@implementation ProductInfoViewController

-(id)initWithProductId:(NSString *)productId {
    if (self = [super init]) {
        self.productId = productId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNaviLeftButton];
    self.rightNaviView.hidden = YES;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    CGFloat viewHeiht = SCREEN_HEIGHT - 64.f;
    CGFloat contentHeight = (self.commentViewContainer.bottom + 10.f) > viewHeiht ? (self.commentViewContainer.bottom + 10.f) : (viewHeiht + 10.f);
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width,  contentHeight);
    _scrollView.delegate = self;
    self.purchaseView.top = viewHeiht-self.purchaseView.height;
    ProductDetailViewController *detailVC = [[ProductDetailViewController alloc] initWithProductId:self.productId];
    [self addChildViewController:detailVC];
    if (detailVC.view != nil) {
        _scrollView.secondScrollView = detailVC.scrollView;
        _scrollView.secondScrollView.delegate = self;
    }
    [self getProductInfo];
}

- (void)getProductInfo {
    [[LKDHud shareHud] showLoadingView];
    [ApiClient getProductDetailInfo:self.productId didFinishLoaded:^(ProdcutDetaiModel *model, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        if ([model.status isEqual:@(1)]) {
            self.productModel = model;
            [self updateProductInfo];
            [self.rightNaviView updateFavoriteInfo:self.productModel.data.in_wishlist];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
    }];
}

- (void)getShopCartNumber {
    [ApiClient getProductNumberInCart:^(CartCountModel *model, NSString *path) {
        if ([model.status isEqual:@(1)]) {
            self.productNumberInCart = model.data.cart_total.integerValue;
            [self.rightNaviView updateShopCartNumber:model.data.cart_total.integerValue];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}

- (void)updateProductInfo {
    [self.picViewContainer addSubview:self.picView];
    NSString *special = self.productModel.data.special;
    if (special.length > 0) {
        self.priceLabel.text = self.productModel.data.special;
        NSMutableAttributedString *attri = [self.productModel.data.price getAttributeStringWithMinddleLine];
        [self.standardPriceLabel setAttributedText:attri];
    } else {
        self.standardPriceLabel.hidden = YES;
        self.standardPriceTipLabel.hidden = YES;
        self.priceLabel.text = self.productModel.data.price;
    }
    [self.priceLabel sizeToFit];
    self.nameLabel.text = self.productModel.data.name;
    if (self.productModel.data.reviews.count > 0) {
        CommentModel *comment = self.productModel.data.reviews[0];
        [self.commenterAvatarIV sd_setImageWithURL:[NSURL URLWithString:(comment.avatar.length > 0 ? comment.avatar : @"")]];
        self.commenterNameLabel.text = comment.firstname;
        self.commentContentLabel.text = comment.text;
    }
}

- (SDCycleScrollView *)picView {
    if (!_picView) {
        NSArray *UrlStringArray = self.productModel.data.images;
        _picView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 417) delegate:nil placeholderImage:nil];
        _picView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        _picView.imageURLStringsGroup = UrlStringArray;
    }
    return _picView;
}

- (ShareView *)shareView {
    if (!_shareView) {
        _shareView = [[ShareView alloc] initWithFrame:self.view.bounds];
        _shareView.hidden = YES;
        __weak typeof(_shareView) weakShareView = _shareView;
        _shareView.closeShareViewBlock = ^(){
            weakShareView.hidden = YES;
        };
        [self.view addSubview:_shareView];
    }
    return _shareView;
}

- (ProductRightNaviView *)rightNaviView {
    if (!_rightNaviView) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _rightNaviView = [[ProductRightNaviView alloc] initWithFrame:CGRectMake(44, 0, width - 44.f, 44.f)];
        __weak typeof(self) weakSelf = self;
        __weak typeof(_rightNaviView) weakNavi = _rightNaviView;
        _rightNaviView.addAttentionBlock = ^() {
            if (!APP_CONTEXT.account) {
                [LoginViewController presentLoginViewController:weakSelf withCompleteBlock:nil];
                return ;
            }
            if (!weakSelf.productModel.data.in_wishlist) {
                [ApiClient addProductToWishList:weakSelf.productId didFinishLoaded:^(KXJson *json, NSString *path) {
                    if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                        [weakSelf showHudWithText:@"关注成功"];
                        [weakNavi updateFavoriteInfo:YES];
                    }
                } didFailLoaded:^(NSError *error, NSString *path) {
                    
                }];
            } else {
                [ApiClient deleteProductFromWishList:weakSelf.productId didFinishLoaded:^(KXJson *json, NSString *path) {
                    if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                        [weakSelf showHudWithText:@"取消关注成功"];
                        [weakNavi updateFavoriteInfo:NO];
                    }
                } didFailLoaded:^(NSError *error, NSString *path) {
                    
                }];
            }
        };
        _rightNaviView.shareBlock = ^(){
            weakSelf.shareView.hidden = NO;
        };
        _rightNaviView.addToShopBagBlock = ^() {
            ShopBagViewController *shopBagVC = [[ShopBagViewController alloc] init];
            shopBagVC.enableBack = YES;
            [weakSelf.navigationController pushViewController:shopBagVC animated:YES];
        };
        [self.navigationController.navigationBar addSubview:_rightNaviView];
    }
    return _rightNaviView;
}

- (void)showHudWithText:(NSString *)str {
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.contentColor = [UIColor blackColor];
    [self.view addSubview:HUD];
    HUD.labelText = str;
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_select_selectd"]] ;
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(2);
    } completionBlock:^{
        [HUD removeFromSuperview];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.rightNaviView.hidden = NO;
    [self getShopCartNumber];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.rightNaviView.hidden = YES;
}

- (IBAction)allCommentsAction:(id)sender {
    MyCommentViewController *commentVC = [[MyCommentViewController alloc] init];
    [self.navigationController pushViewController:commentVC animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int currentPostion = scrollView.contentOffset.y;
    if ((currentPostion - self.lastPosition > 25) && currentPostion > 0) {
        self.lastPosition = currentPostion;
        [UIView animateWithDuration:.5f animations:^{
            self.purchaseView.top = self.view.height;
        }];
    }else if ((self.lastPosition - currentPostion > 25)) {
        self.lastPosition = currentPostion;
        [UIView animateWithDuration:.5f animations:^{
            self.purchaseView.top = self.view.height - self.purchaseView.height;
        }];
    }
    if ([scrollView isEqual:self.scrollView.secondScrollView] &&  ((scrollView.contentOffset.y + scrollView.height) >= scrollView.contentSize.height)) {
        self.bottomBtn.alpha = 1.f;
    }
}

- (IBAction)topAction:(id)sender {
    self.scrollView.contentOffset = CGPointMake(0, 0);
    self.bottomBtn.alpha = 0.f;
}

- (IBAction)addToShopBag:(id)sender {
    NSMutableDictionary *options = [NSMutableDictionary dictionary];
    [[LKDHud shareHud] showLoadingView];
    if (self.productModel.data.options.count > 0) {
        for (ProductOptionModel *optionModel in self.productModel.data.options) {
            ProductOptionValueModel *optionValueModel = [optionModel.product_option_value objectAtIndex:0];
            [options setObject: optionValueModel.product_option_value_id  forKey:[NSString stringWithFormat:@"%@", optionModel.product_option_id]];
        }
    }
    [ApiClient addProductToShopBag:self.productId quantity:1 options:options didFinishLoaded:^(KXJson *json, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
            [self showHudWithText:@"添加成功"];
            [self.rightNaviView updateShopCartNumber:++self.productNumberInCart];
            [self getShopCartNumber];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
    }];
}

- (PurchaseNowViewController *)purchaseVC {
    if (!_purchaseVC) {
        _purchaseVC = [[PurchaseNowViewController alloc] initWithProductModel:self.productModel];
        _purchaseVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f];
        _purchaseVC.delegate = self;
    }
    return _purchaseVC;
}

- (IBAction)buyNowAction:(id)sender {
    if(!APP_CONTEXT.account) {
        [LoginViewController presentLoginViewController:self withCompleteBlock:nil];
        return;
    }
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:self.purchaseVC];
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        navi.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }else{
        self.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;
    [controller presentViewController:navi animated:YES completion:^{
        
    }];
}

- (void)closePurchaseViewController:(PurchaseNowViewController *)purchaseVC {
    [self.purchaseVC dismissViewControllerAnimated:YES completion:^{
        self.purchaseVC = nil;
    }];
}

@end
